/*******************************************************************************
 * Copyright (c) 2012 Alexandr Tsvetkov.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Contributors:
 *     Alexandr Tsvetkov - initial API and implementation
 *
 * Project:
 *     TAO Library
 *
 * File name:
 *     Util.java
 *
 * License agreement:
 *
 * 1. This code is published AS IS. Author is not responsible for any damage that can be
 *    caused by any application that uses this code.
 * 2. Author does not give a garantee, that this code is error free.
 * 3. This code can be used in NON-COMMERCIAL applications AS IS without any special
 *    permission from author.
 * 4. This code can be modified without any special permission from author IF AND ONLY IF
 *    this license agreement will remain unchanged.
 * 5. SPECIAL PERMISSION for this code usage in COMMERCIAL application SHOULD be obtained
 *    from author.
 ******************************************************************************/
package ua.at.tsvetkov.strings;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import ua.at.tsvetkov.util.Log;

public class Util {

	/**
	 * Очистка строки от мусора
	 * 
	 * @param src
	 * @return
	 */
	public static String removeHtmlTag(String src) {
		if (src == null)
			return null;
		return src.replaceAll("&nbsp;", " ").replaceAll("<.*?>|Ђ|ђ|&shy;", "").replaceAll("&quot;", "\"");
	}

	public static String[] split(String src, char ch) {
		if (src == null || src.length() == 0) {
			return new String[0];
		}
		char[] chars = src.toCharArray();
		ArrayList<String> data = new ArrayList<String>();
		for (int i = 0; i <= chars.length; i++) {
			String st = "";
			while (i < chars.length && chars[i] != ch) {
				st += chars[i++];
			}
			data.add(st);
		}
		return data.toArray(new String[data.size()]);
	}

	/**
	 * Разделяет строку форматированную символом '|' на массв полей. Конечный массив будет иметь количество полей = count. Нехватающие поля заполняются пустой строкой. Если в форматированной строке
	 * больше полей, чем указано count, то они отбрасываются.
	 * 
	 * @param st форматированная строка
	 * @param count предопределенное колчество полей.
	 * @return
	 */
	public static String[] split(String st, int count) {
		if (st != null) {
			String[] data = st.split("\\|");
			if (data.length == count) {
				return data;
			} else {
				String[] newData = new String[count];
            if (data.length > count) {
                System.arraycopy(data, 0, newData, 0, count);
            } else {
                System.arraycopy(data, 0, newData, 0, data.length);
            }
            for (int i = data.length; i < newData.length; i++) {
                newData[i] = "";
            }
            return newData;
			}
		} else {
			return null;
		}
	}

	/**
	 * This functions returns a MD5 hash based on the input String
	 * 
	 * @param input String to be MD5
	 * @return the MD5 hash
	 */
	public static String getMd5(String input) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] messageDigest = md.digest(input.getBytes());
			BigInteger number = new BigInteger(1, messageDigest);
			String md5 = number.toString(16);

			while (md5.length() < 32) {
				md5 = "0" + md5;
			}
			return md5;
		} catch (NoSuchAlgorithmException e) {
			Log.e(e);
			return null;
		}
	}

	/**
	 * Return string representation of the int constant in class.
	 * 
	 * @param c
	 * @param val
	 * @return
	 */
	public static String getName(Class<?> c, int val) {
		try {
			for (Field f : c.getDeclaredFields()) {
				int mod = f.getModifiers();
				if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Modifier.isFinal(mod) && val == (Integer) f.get(null)) {
					return f.getName();
				}
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return "";
	}

}
